import {
  useState,
  useEffect,
  forwardRef,
  useImperativeHandle,
  useRef,
} from 'react';
import {
  Modal,
  Form,
  Input,
  Radio,
  DatePicker,
  Select,
  Checkbox,
  InputNumber,
  message,
} from 'antd';
const { RangePicker } = DatePicker;
const { TextArea } = Input;

interface FormItem {
  label: string;
  field: string;
  component: string;
  span?: number;
  componentProps?: any;
}

interface DynamicModalProps {
  form: FormItem[];
  rules?: any;
  refresh?: () => void;
}

const DynamicModal = forwardRef((props: DynamicModalProps, ref) => {
  const [visible, setVisible] = useState(false);
  const [title, setTitle] = useState('新增');
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState<any>({});
  const formRef = useRef(null);

  useImperativeHandle(ref, () => ({
    handleVisible: (visible: boolean, name: string, data?: any) => {
      setVisible(visible);
      setTitle(name);
      if (name !== '新增' && data) {
        setFormData(data);
      }
    },
  }));

  const handleOk = async () => {
    setLoading(true);
    try {
      const values = await formRef.current?.validateFields();
      // 这里调用你的API方法
      if (title === '新增') {
        // await moduleApi.ondutyAdd(values);
        message.success('新增成功');
      } else {
        // await moduleApi.ondutyEdit(values);
        message.success('编辑成功');
      }
      props.refresh?.();
      setVisible(false);
    } catch (error) {
      console.error('表单验证失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    formRef.current?.resetFields();
    setFormData({});
    setVisible(false);
  };

  const renderFormItem = (item: FormItem) => {
    const commonProps = {
      ...item.componentProps,
      key: item.field,
      placeholder: `请输入${item.label}`,
      style: { width: '100%' },
    };

    switch (item.component) {
      case 'Input':
        return <Input {...commonProps} />;
      case 'Radio':
        return (
          <Radio.Group {...commonProps}>
            {item.componentProps?.options?.map((opt: any) => (
              <Radio key={opt.value} value={opt.value}>
                {opt.label}
              </Radio>
            ))}
          </Radio.Group>
        );
      case 'RangePicker':
        return (
          <RangePicker {...commonProps} showTime format="YYYY-MM-DD HH:mm:ss" />
        );
      case 'ApiSelect':
        return (
          <Select
            {...commonProps}
            options={item.componentProps?.options}
            fieldNames={{ label: 'label', value: 'value' }}
          />
        );
      case 'textarea':
        return <TextArea {...commonProps} rows={4} />;
      case 'Checkbox':
        return (
          <Checkbox.Group {...commonProps}>
            {item.componentProps?.options?.map((opt: any) => (
              <Checkbox key={opt.value} value={opt.value}>
                {opt.label}
              </Checkbox>
            ))}
          </Checkbox.Group>
        );
      case 'InputNumber':
        return <InputNumber {...commonProps} style={{ width: '100%' }} />;
      default:
        return null;
    }
  };

  return (
    <Modal
      open={visible}
      title={title}
      onOk={handleOk}
      onCancel={handleCancel}
      width="50%"
      confirmLoading={loading}
      footer={title === '详情' ? null : undefined}
    >
      <Form
        ref={formRef}
        layout="vertical"
        initialValues={formData}
        onValuesChange={(changedValues) =>
          setFormData((prev) => ({ ...prev, ...changedValues }))
        }
      >
        <div
          style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(24, 1fr)',
            gap: '16px',
          }}
        >
          {props.form.map((item) => (
            <div
              key={item.field}
              style={{ gridColumn: `span ${item.span || 24}` }}
            >
              <Form.Item
                label={item.label}
                name={item.field}
                rules={props.rules?.[item.field]}
              >
                {renderFormItem(item)}
              </Form.Item>
            </div>
          ))}
        </div>
      </Form>
    </Modal>
  );
});

export default DynamicModal;
